package com.whpu.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created by RiceBall on 2020/10/13 11:17
 */

@Aspect
@Component
public class LogAspect {

    private long startTime = 0L;
    private long endTime = 0L;
    Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution (public * com.whpu.service.impl.*.*(..))")
    public void serviceAspect() {
    }

    @Before("serviceAspect()")
    public void restLogAccess(JoinPoint joinPoint) {
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String url = requestAttributes.getRequest().getRequestURI();
        String remoteAddr = requestAttributes.getRequest().getRemoteAddr();
        logger.info("[WEB] remoteAddr: {},  URL: {}, args: {}", remoteAddr, url, joinPoint.getArgs());
    }

    @After("serviceAspect()")
    public void after(JoinPoint joinPoint) {
        endTime = System.currentTimeMillis();
        logger.debug("{}",joinPoint.getTarget().getClass().getName());
        logger.info("[web] method: {} , time: {}", joinPoint.getTarget(), endTime - startTime);

    }

    @AfterThrowing(value = "serviceAspect()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e) {
        String methodName = joinPoint.getSignature().getName();
        logger.error("异常的方法：{} ,异常信息：",methodName,e);
    }


}
